package com.atgugui.servicebase.exceptionhandler;

import com.atgugui.commonutils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 定义统一的异常类
 */
@ControllerAdvice
@Slf4j // 将异常写入到文件中(logback方式实现异常的写入)
public class GlobalExceptionHandler {
    /**
     * 定义全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return Result.error().data("excpetion","发生Exception类型的异常了");
    }

    /**
     * 定义特殊异常
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result error(ArithmeticException e) {
        e.printStackTrace();
        return Result.error().data("exception","发生了ArithmeticException异常");
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(GuLiException.class)
    @ResponseBody
    public Result error(GuLiException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.error().code(e.getCode()).message(e.getMsg());
    }
}
